package com.lianyu.wangyiyun.utils;

import android.app.Activity;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;

/**
 * 监听软键盘是否弹出
 *
 * @author Chen Yuguang
 * @date 2021/6/16 2:55
 */
public class KeyboardChangeListener implements ViewTreeObserver.OnGlobalLayoutListener {
    private View mContentView;
    private int oldDiff = 0;
    private final Rect r = new Rect();
    private KeyBoardListener mKeyBoardListener;

    public interface KeyBoardListener {
        /**
         * 软键盘状态改变的回调接口
         *
         * @param isShow 软键盘是否弹起
         */
        void onKeyboardChange(boolean isShow);
    }

    public void setKeyBoardListener(KeyBoardListener keyBoardListener) {
        mKeyBoardListener = keyBoardListener;
    }

    public KeyboardChangeListener(Activity activity, KeyBoardListener keyBoardListener) {
        if (activity == null) {
            return;
        }
        mKeyBoardListener = keyBoardListener;
        mContentView = activity.getWindow().getDecorView();
        if (mContentView != null) {
            mContentView.getViewTreeObserver().addOnGlobalLayoutListener(this);
        }
    }

    @Override
    public void onGlobalLayout() {
        mContentView.getWindowVisibleDisplayFrame(r);
        int diff = mContentView.getHeight() - r.height();
        //键盘是否弹出
        boolean isShow = (diff > 200);
        if (diff != oldDiff) {
            oldDiff = diff;
            if (mKeyBoardListener != null) {
                mKeyBoardListener.onKeyboardChange(isShow);
            }
        }
    }

    public void removeListener() {
        mContentView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }

}
